package com.example.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.example.SwingArea;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author user
 */
@Slf4j
public class BatUtils {
    private static ThreadPoolExecutor executor = null;

    static {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("cmd-pool-%d").build();
        //根据实际情况创建线程池
        executor = new ThreadPoolExecutor(6, 10, 5,
                TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(1024),
                namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
    }


    /**
     * 流处理
     */
    private static void clearStream(final InputStream stream) {
        //处理buffer的线程
        executor.execute(new Runnable() {
            @Override
            public void run() {

                String line = null;
                try (BufferedReader in = new BufferedReader(new InputStreamReader(stream, "GB2312"));) {
                    while ((line = in.readLine()) != null) {
                        if (StrUtil.isEmptyIfStr(line)){
                            continue;
                        }
                        String time = DateUtil.format(new Date(), "MM-dd HH:mm:ss");
                        SwingArea.tableModel.addRow(new Object[]{time, line});
                    }
                } catch (IOException e) {
                    log.error("exec error : {}", e);
                }
            }
        });
    }

    public static boolean execCommand(String locationCmd) {
        boolean flg = true;
        Process process = null;
        try {
            String startTime = DateUtil.format(new Date(), "MM-dd HH:mm:ss");
            SwingArea.tableModel.addRow(new Object[]{startTime, StrUtil.format("开始执行{}", locationCmd)});
            process = Runtime.getRuntime().exec(locationCmd);


            //消费正常日志
            clearStream(process.getInputStream());
            //消费错误日志
            clearStream(process.getErrorStream());

            String endTime = DateUtil.format(new Date(), "MM-dd HH:mm:ss");
            if (process.waitFor() != 0) {
                if (process.exitValue() == 1) {
                    SwingArea.tableModel.addRow(new Object[]{endTime, "脚本执行失败!"});
                    flg = false;
                }
            }
            SwingArea.tableModel.addRow(new Object[]{endTime, "脚本执行成功"});
            if (SwingArea.stopFlag){
                SwingArea.stopFlag = false;
                SwingArea.tableModel.addRow(new Object[]{endTime, "脚本停止运行"});
                throw new RuntimeException();
            }

        } catch (IOException | InterruptedException e) {
            log.error(e.toString());
            flg = false;
        } finally {
            if (process != null) {
                // 销毁当前进程，阻断当前命令执行
                long pid = process.pid();
//                process.toHandle().destroyForcibl();
            }
        }
        return flg;
    }
}
